<template>
  <div>
    <div class="container" v-if="!showcheckreport">
      <div class="container-search">
        <!-- <div class="container-search-top"></div> -->
        <div class="container-search-bottom">
          <!-- 筛选条件 -->
          <div class="search">
            <div class="search-item">
              <el-input
                v-model="params.name"
                placeholder="请输入单位名称"
                clearable
                maxlength="25"
                class="search-input"
              />
            </div>
            <div class="search-item">
              <el-cascader
                v-model="params.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                @change="handlerregion"
                :props="areaprops"
              />
            </div>
            <div class="search-item">
              <el-select
                v-model="params.typeId"
                placeholder="请选择单位类型"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unittypeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.levelId"
                placeholder="请选择单位级别"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unitlevelList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.industryId"
                placeholder="请选择所属行业"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in supervisorList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-button type="primary" @click="gettaskList"
                ><img src="@/assets/images/search.png" alt="" /> 搜索</el-button
              >
              <el-button color="#eff3ff" :dark="true" @click="reset(1)"
                ><img src="@/assets/images/reset.png" alt="" />
                <span style="color: #6d98fd">重置 </span>
              </el-button>
              <el-button
                type="primary"
                @click="addtask"
                v-if="[0, 2].includes(userStore.deptType)"
                ><img src="@/assets/images/add.png" alt="" />创建任务</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="container-button"></div> -->

      <div class="container-table">
        <!-- 表格筛选 -->
        <div class="filter">
          <div
            class="filter-item"
            :class="activeindex === '' ? 'active' : ''"
            @click="handlerfilter('')"
          >
            <img
              src="@/assets/images/all.png"
              alt=""
              srcset=""
              v-if="activeindex === ''"
            />
            <img src="@/assets/images/blueall.png" alt="" srcset="" v-else />
            <div class="item-text">全部 （{{ alldata || 0 }}）</div>
          </div>
          <div
            class="filter-item"
            :class="activeindex === 0 ? 'active' : ''"
            @click="handlerfilter(0)"
          >
            <img
              src="@/assets/images/waitcheck.png"
              alt=""
              srcset=""
              v-if="activeindex === 0"
            />
            <img
              src="@/assets/images/bluewaitcheck.png"
              alt=""
              srcset=""
              v-else
            />

            <div class="item-text">待检查 （{{ notInspect || 0 }}）</div>
          </div>
          <div
            class="filter-item"
            :class="activeindex == 1 ? 'active' : ''"
            @click="handlerfilter(1)"
          >
            <img
              src="@/assets/images/check.png"
              alt=""
              srcset=""
              v-if="activeindex == 1"
            />
            <img src="@/assets/images/bluecheck.png" alt="" srcset="" v-else />

            <div class="item-text">已检查 （{{ inspected || 0 }}）</div>
          </div>
        </div>
        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="taskList"
          border
          height="58vh"
          :header-cell-style="{ 'text-align': 'center' }"
          @sort-change="sortChange"
        >
          <el-table-column
            label="操作"
            :show-overflow-tooltip="true"
            width="150"
            :resizable="false"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <span class="detail" @click="handleOperate('detail', row)"
                  >详情</span
                >
                <span
                  class="edit"
                  @click="handleOperate('check', row)"
                  v-if="[1].includes(userStore.deptType) && row.taskStatus == 0"
                  >检查</span
                >
                <span
                  class="delete"
                  @click="handleOperate('delete', row)"
                  v-if="
                    userStore.deptId == row.belongDeptId && row.taskStatus == 0
                  "
                  >删除</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="单位名称"
            prop="name"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="行政区划"
            prop="areaName"
            width="300"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="单位类型"
            prop="institutionType"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.institutionType || "--" }}
            </template>
          </el-table-column>
          <el-table-column
            label="所属行业"
            prop="industryName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="所属派出所"
            prop="policeStationName"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.policeStationName || "--" }}
            </template>
          </el-table-column>
          <el-table-column
            label="单位负责人"
            prop="leader"
            :show-overflow-tooltip="true"
            width="120"
            sortable="custom"
          >
          </el-table-column>

          <el-table-column
            label="截止时间"
            prop="lastDate"
            :show-overflow-tooltip="true"
            width="180"
            sortable="custom"
          >
            <template #default="{ row }">
              {{ row.lastDate.slice(0, 10) }}
            </template>
          </el-table-column>
          <el-table-column
            label="检查状态"
            prop=""
            width="220"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <div class="check-tab">
                <div class="tab-item" v-if="row.taskStatus == 0">
                  <div class="tab orange">待检查</div>
                  <div class="tab-time orange">{{ row.taskDate }}</div>
                </div>
                <div class="tab-item" v-if="row.taskStatus == 1">
                  <div class="tab green">已检查</div>
                  <div class="tab-time green">
                    {{ row.taskDate && row.taskDate.slice(0, 10) }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          class="pagination"
          :total="total"
          v-model:page="params.pageNum"
          v-model:limit="params.pageSize"
          @pagination="gettaskList"
        />
      </div>
    </div>
    <!-- 创建任务弹窗 -->
    <el-dialog
      v-model="showTaskadd"
      width="460px"
      append-to-body
      class="dialogBox"
      @close="Taskaddclose"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">创建任务</div>
        </div>
      </template>
      <div class="task-form">
        <el-form
          v-if="showTaskadd"
          :model="taskForm"
          ref="taskFormRef"
          :rules="queryRules"
          label-width="130px"
          label-position="top"
        >
          <el-form-item label="添加单位：" prop="addunit" label-width="130">
            <div class="addunit">
              <div class="addunit-btn" v-if="!importsuccess">
                <el-button
                  type="primary"
                  @click="handlerimport(1)"
                  v-if="!selectsuccess"
                  >&nbsp;&nbsp;&nbsp; 导入&nbsp;&nbsp;&nbsp;
                </el-button>
                <el-button
                  @click="handlerimport(2)"
                  color="#efbf00"
                  v-if="!importsuccess"
                >
                  <span style="color: #ffffff">智能遴选</span>
                </el-button>
              </div>
              <div
                class="guide"
                @click="handlerimport(3)"
                v-if="importsuccess || selectsuccess"
              >
                已添加{{ normalData.length }}家企业 >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="截止时间：" prop="lastDate" label-width="130">
            <el-date-picker
              v-model="taskForm.lastDate"
              value-format="YYYY-MM-DD"
              class="search-input"
              type="date"
              placeholder="请选择截止时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="情况说明：" prop="remark" label-width="130">
            <el-input
              type="textarea"
              maxlength="500"
              v-model="taskForm.remark"
              placeholder="请填写原因"
              clearable
              class="search-input"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitaddtask"> 确认</el-button>
          <el-button @click="Taskaddclose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入弹窗 -->
    <el-dialog
      v-model="showImport"
      :width="showuploadtable ? '860px' : '460px'"
      append-to-body
      class="dialogBox ImportdialogBox"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="!showuploadtable"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">导入</div>
        </div>
      </template>
      <div class="Import" v-if="!showuploadtable">
        <div class="Import-title">
          <div class="item">
            <div class="title">导入模板</div>
            <div class="text" style="cursor: pointer" @click="download">
              单位名录导入模板.xls
            </div>
          </div>
          <div class="item">
            <div class="title">导入提示</div>
            <div class="text">
              请确保数据严格按照导入模板填报，否则将视为异常数据！
            </div>
          </div>
        </div>
        <div class="Import-upload">
          <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            multiple
            accept=".xls,.xlsx"
            :headers="myHeaders"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <img src="@/assets/images/upload-icon.png" alt="" />
            <div class="el-upload__text">点击或将文件拖拽到这里上传</div>
          </el-upload>
          <el-progress
            v-if="isUpload"
            status="success"
            :percentage="100"
            :format="format"
            :indeterminate="true"
            style="width: 80%"
          />
        </div>
      </div>
      <div class="Import-table" v-else>
        <div class="table-text">
          请核实以上数据的准确性，重复数据被覆盖，异常数据无法导入！
        </div>
        <div class="table-text">
          正常数据 {{ normalData.length }} 条，重复数据
          {{ repeatData.length }} 条，异常数据 {{ abnormalData.length }} 条，
        </div>
        <el-table
          :data="ImporttableList"
          border
          height="40vh"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column
            label="操作"
            :show-overflow-tooltip="true"
            fixed="right"
            :resizable="false"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <span class="delete" @click="importdelete(row)">删除</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="单位名称"
            prop="name"
            :show-overflow-tooltip="true"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="社会信用代码"
            prop="unifiedSocialCreditCode"
            width="300"
            :show-overflow-tooltip="true"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="数据状态"
            prop="institutionType"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template #default="{ row }">
              <div v-if="row.typeId == 2">
                <span>正常</span>
              </div>
              <div v-if="row.typeId == 1">
                <span>重复</span><img src="@/assets/images/Lament.png" alt="" />
              </div>
              <div v-if="row.typeId == 0">
                <span>异常</span><img src="@/assets/images/Lament.png" alt="" />
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <pagination
          class="pagination"
          :total="importparams.total"
          v-model:page="importparams.pageNum"
          v-model:limit="importparams.pageSize"
          @pagination="gettaskList"
        /> -->
        <!-- @size-change="handleimportSizeChange" -->
        <el-pagination
          v-model:current-page="importPage"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="importtotal"
          :background="true"
          @current-change="handleimportPageChange"
        />
      </div>
      <template #footer v-if="showuploadtable">
        <div class="dialog-footer">
          <el-button type="primary" @click="importsubimt">确 定</el-button>
          <el-button @click="importcancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 智能遴选 -->
    <el-dialog
      v-model="showselect"
      width="1400px"
      append-to-body
      class="dialogBox"
      @close="reset(2)"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">智能遴选</div>
        </div>
      </template>
      <div class="ai-select">
        <div class="select-left">
          <div class="item">
            <div class="title">单位名称：</div>
            <div class="content">
              <el-input
                v-model="unitparams.name"
                placeholder="请输入单位名称"
                clearable
                maxlength="25"
                class="search-input"
              />
            </div>
          </div>
          <div class="item">
            <div class="title">所在区域：</div>
            <div class="content">
              <el-cascader
                v-model="unitparams.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                style="width: 100%"
                @change="handlerregion"
                :props="areaprops"
              />
            </div>
          </div>
          <div class="item">
            <div class="title">单位类型：</div>
            <div class="content">
              <el-select
                v-model="unitparams.typeId"
                placeholder="请选择单位类型"
                clearable
                class="search-input"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in unittypeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue * 1"
                />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="title">单位级别：</div>
            <div class="content">
              <el-select
                v-model="unitparams.levelId"
                placeholder="请选择单位级别"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in unitlevelList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="title">所属行业：</div>
            <div class="content">
              <el-select
                v-model="unitparams.industryId"
                placeholder="请选择所属行业"
                clearable
                style="width: 100%"
                placement="right"
              >
                <el-option
                  v-for="dict in supervisorList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="title">最近检查：</div>
            <div class="content">
              <el-select
                ref="selectRef"
                v-model="unitparams.checkNumber"
                placeholder="请选择"
                clearable
                style="width: 100%"
                @clear="clearcustom"
              >
                <el-option
                  v-for="dict in checktimeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
                <el-option disabled value="">
                  <span>自定义大于</span>
                  <el-input
                    type="number"
                    v-model="unitparams.checkDate"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    placeholder="请输入"
                    clearable
                    maxlength="25"
                    style="width: 100px"
                    @keydown.enter="handlercustom"
                  />
                  <span>个月</span>
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="item-btn">
            <el-button type="primary" @click="getunitList"
              ><img src="@/assets/images/search.png" alt="" /> 搜索</el-button
            >
            <el-button color="#eff3ff" :dark="true" @click="reset(2)"
              ><img src="@/assets/images/reset.png" alt="" />
              <span style="color: #6d98fd">重置 </span>
            </el-button>
          </div>
        </div>
        <div class="select-middle">
          <div class="middle-top">
            <div class="middle-title">
              <img src="@/assets/images/title-icon.png" alt="" />
              筛选结果 <span>（共{{ unittotal }}家）</span>
            </div>
            <div class="middle-button">
              <el-button type="primary" @click="handlerselectunit"
                >确认选择</el-button
              >
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="unitList"
            border
            height="52vh"
            :header-cell-style="{ 'text-align': 'center' }"
            ref="multipleTableRef"
            @selection-change="handleSelectionChange"
            :row-key="getRowKey"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :reserve-selection="true"
            />
            <el-table-column
              label="单位名称"
              prop="name"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="单位类型"
              prop="institutionType"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="所属行业"
              prop="industryName"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="最近检查时间"
              prop="lastCheckTime"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            class="pagination"
            :total="unittotal"
            v-model:page="unitparams.pageNum"
            v-model:limit="unitparams.pageSize"
            @pagination="getunitList"
          />
        </div>
        <div class="select-right">
          <div class="right-top">
            <div class="middle-title">
              <img src="@/assets/images/title-icon.png" alt="" />
              已选择 <span>（共{{ selectarray.length }}家）</span>
            </div>
          </div>
          <div class="right-content">
            <div
              class="content-item"
              v-for="(item, index) in selectarray"
              :key="index"
            >
              <div class="item-text"># {{ item.name }} #</div>
              <img
                src="@/assets/images/close.png"
                alt=""
                srcset=""
                @click="deleteArray(item, index)"
              />
            </div>
          </div>
          <div class="content-btn">
            <el-button type="primary" @click="handlerselectunit">
              确认</el-button
            >
            <el-button type="info" @click="showselect = false">
              <span>取消</span>
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 单位清单 -->
    <el-dialog
      v-model="showinventory"
      width="1400px"
      append-to-body
      class="dialogBox ImportdialogBox"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">单位清单</div>
        </div>
      </template>
      <div class="Import-table">
        <el-table
          v-loading="loading"
          :data="inventorydata"
          border
          height="49vh"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column
            type="index"
            label="序号"
            :index="inventoryindexMethod"
            width="70"
            align="center"
          />
          <el-table-column
            label="操作"
            :show-overflow-tooltip="true"
            fixed="right"
            :resizable="false"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <span class="delete" @click="inventorydelete(row)">删除</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="单位名称"
            prop="name"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="行政区划"
            prop="areaName"
            width="300"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="单位类型"
            prop="institutionType"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="单位级别"
            prop="levelName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="所属行业"
            prop="industryName"
            :show-overflow-tooltip="true"
            width="180"
          >
          </el-table-column>
          <el-table-column
            label="最近检查时间"
            prop="lastCheckTime"
            :show-overflow-tooltip="true"
            width="180"
          >
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="inventoryparams.pageNum"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="normalData.length"
          :background="true"
          @current-change="handleinventoryPageChange"
        />
      </div>
    </el-dialog>
    <!-- 检查记录详情 -->
    <el-dialog
      v-model="showdialog"
      width="1000px"
      append-to-body
      class="dialogBox"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">任务详情</div>
        </div>
      </template>
      <Taskdtl ref="taskdetailref" pageType="task" v-if="showdialog"></Taskdtl>
    </el-dialog>
    <!-- 检查上报 -->
    <Checkreport
      ref="checkreportref"
      v-if="showcheckreport"
      v-model:showcheckreport="showcheckreport"
      @refreshList="reset"
    ></Checkreport>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import Card from "@/components/Card";
import Taskdtl from "./taskdtl";
import Checkreport from "./checkreport";
import { getinstitutionlist, delinstitution } from "@/api/erp/unit";
import {
  gettasklist,
  addtasklist,
  downloadTemplate,
  deltasklist,
  getcheckRecordCount,
} from "@/api/task/task";
import { getDictsApi, getAreaList } from "@/api/dict";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import { useRouter } from "vue-router";
const router = useRouter();

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

// 搜索参数
let params = reactive({
  pageNum: 1,
  pageSize: 20,
  name: "",
  typeId: "",
  levelId: "",
  industryId: "",
  region: [],
  provinceId: "",
  cityId: "",
  zoneId: "",
  streetId: "",
});
// 搜索参数
let unitparams = reactive({
  pageNum: 1,
  pageSize: 20,
  name: "",
  typeId: "",
  levelId: "",
  industryId: "",
  checkNumber: "",
  checkDate: "",
  region: [],
  provinceId: "",
  cityId: "",
  zoneId: "",
  streetId: "",
});
//导入数据列表
let importparams = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});
let inventoryparams = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
let inventorydata = ref([]);
// 总数
const total = ref(0);
//智能遴选
const unittotal = ref(0);

//行政区划数据
let options = ref([]);

const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    console.log("node", node);
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 3,
            // disabled: true, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};

// 表格加载效果
const loading = ref(false);
const showTaskadd = ref(false);
const showImport = ref(false);
const showselect = ref(false);
const showinventory = ref(false);
const importsuccess = ref(false);
const selectsuccess = ref(false);
let showcheckreport = ref(false);
//任务列表
const taskList = ref([]);
// 项目列表
const unitList = ref([]);
//所有数据
let allData = ref([]);
//导入分页数据
let ImporttableList = ref([]);
//正常的数据
let normalData = ref([]);
//重复的数据
let repeatData = ref([]);
//异常的数据
let abnormalData = ref([]);

// 单位类型下拉
const unittypeList = ref([]);
// 单位级别下拉
const unitlevelList = ref([]);
// 所属行业下拉
const supervisorList = ref([]);
//检查时间下拉
const checktimeList = ref([]);
// 详情弹窗的显隐
let showdialog = ref(false);
//上传成功展示预览
let showuploadtable = ref(false);
const uploadUrl =
  import.meta.env.VITE_APP_BASE_API + "/system/institution/import";

const myHeaders = ref({
  Authorization: "Bearer " + getToken(),
});

//选中的项
let activeindex = ref("");

//创建任务表单
let taskForm = ref({});

//导入数据的分页数据
let importPage = ref(1);
let importtotal = ref(0);

//智能遴选选中数据
let selectarray = ref([]);

//详情组件的引用
const taskdetailref = ref(null);
//检查上报的引用
const checkreportref = ref(null);
//省市区校验规则
const addunitValidate = (rule, value, callback) => {
  if (normalData.value.length == 0) {
    callback(new Error("请添加单位"));
  } else {
    callback();
  }
};
const queryRules = ref({
  addunit: [
    {
      required: true,
      validator: addunitValidate,
      message: "请添加单位",
      trigger: "change",
    },
  ],
  lastDate: [{ required: true, message: "请选择截止时间", trigger: "change" }],
});

/**
 * @description: 处理自定义月份
 * @param {Number} index 索引
 */
const selectRef = ref(null);
const handlercustom = () => {
  selectRef.value.blur();
  console.log("总定义", unitparams);
  unitparams.checkNumber = "自定义大于" + unitparams.checkDate + "个月";
};
/**
 * @description: 清除自定义月份
 * @param {Number} index 索引
 */
const clearcustom = () => {
  console.log("chulai ");
  unitparams.checkDate = "";
};
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function inventoryindexMethod(index) {
  const currentPage = inventoryparams.value.pageNum;
  const pageSize = inventoryparams.value.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  console.log("column", column);
  if (column.prop == "lastDate" && column.order) {
    params.sortField = "a.last_date";
  } else if (column.prop == "leader" && column.order) {
    params.sortField = "b.leader";
  } else {
    params.sortField = "";
  }
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else if (column.order === "ascending") {
    params.sortOrder = "ASC"; // 排序或倒序
  } else {
    params.sortOrder = "";
  }
  gettaskList();
};

/**
 * @description: 处理分页
 */
const handleimportPageChange = (value) => {
  displayData(value);
};

/**
 * @description: 处理清单分页
 */
const handleinventoryPageChange = (value) => {
  inventorydisplayData(value);
};

// 显示指定页的数据
const displayData = (page) => {
  let itemsPerPage = 10;
  const startIndex = (page - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  ImporttableList.value = allData.value.slice(startIndex, endIndex);
  importtotal.value = allData.value.length;
  normalData.value = allData.value.filter((item) => {
    return item.typeId == 2;
  });
  repeatData.value = allData.value.filter((item) => {
    return item.typeId == 1;
  });
  abnormalData.value = allData.value.filter((item) => {
    return item.typeId == 0;
  });
};

// 显示指定页的数据
const inventorydisplayData = (page) => {
  let itemsPerPage = 10;
  const startIndex = (page - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  inventorydata.value = normalData.value.slice(startIndex, endIndex);
};
/**
 * @description: 表格数据接口
 */
let finishtaskList = ref([]);
const gettaskList = () => {
  loading.value = true;
  gettasklist(
    { pageNum: params.pageNum, pageSize: params.pageSize },
    params
  ).then((res) => {
    taskList.value = res.rows;
    total.value = res.total;
    loading.value = false;
    checkRecordCount();
  });
};
/**
 * @description: 获取状态数据
 */
let alldata = ref(0);
let notInspect = ref(0);
let inspected = ref(0);
const checkRecordCount = () => {
  getcheckRecordCount(
    { pageNum: params.pageNum, pageSize: params.pageSize },
    params
  ).then((res) => {
    alldata.value = res.data.allData;
    notInspect.value = res.data.notInspect;
    inspected.value = res.data.inspected;
  });
};

/**
 * @description: 智能遴选数据接口
 */
const getunitList = () => {
  console.log("unitparams", unitparams);
  let obj = JSON.parse(JSON.stringify(unitparams));
  if (obj.checkNumber.length > 6) {
    obj.checkNumber = "5";
  }
  loading.value = true;
  getinstitutionlist(
    { pageNum: unitparams.pageNum, pageSize: unitparams.pageSize },
    obj
  ).then((res) => {
    unitList.value = res.rows;
    unittotal.value = res.total;
    loading.value = false;
  });
};

/**
 * @description: 重置
 */
const reset = (type) => {
  switch (type) {
    case 1:
      Object.assign(params, {
        pageNum: 1,
        pageSize: 20,
        name: "",
        typeId: "",
        levelId: "",
        industryId: "",
        taskStatus: "",
        region: [],
        provinceId: "",
        cityId: "",
        zoneId: "",
        streetId: "",
      });
      activeindex.value = "";
      gettaskList();
      break;
    case 2:
      Object.assign(unitparams, {
        pageNum: 1,
        pageSize: 20,
        name: "",
        typeId: "",
        levelId: "",
        industryId: "",
        checkNumber: "",
        checkDate: "",
        region: [],
        provinceId: "",
        cityId: "",
        zoneId: "",
        streetId: "",
      });
      getunitList();
      break;
    default:
      break;
  }
  checkRecordCount();
  // gettaskList();
};

/**
 * @description: tab操作
 */
const handlerfilter = (index) => {
  activeindex.value = index;
  params.taskStatus = index;
  gettaskList();
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (showselect.value) {
    if (value) {
      switch (value.length) {
        case 1:
          unitparams.provinceId = value[0];
          break;
        case 2:
          unitparams.provinceId = value[0];
          unitparams.cityId = value[1];
          break;
        case 3:
          unitparams.provinceId = value[0];
          unitparams.cityId = value[1];
          unitparams.zoneId = value[2];
          break;
        case 4:
          unitparams.provinceId = value[0];
          unitparams.cityId = value[1];
          unitparams.zoneId = value[2];
          unitparams.streetId = value[3];
          break;

        default:
          break;
      }
    } else {
      unitparams.region = [];
      unitparams.provinceId = null;
      unitparams.cityId = null;
      unitparams.zoneId = null;
      unitparams.streetId = null;
    }
  } else {
    if (value) {
      switch (value.length) {
        case 1:
          params.provinceId = value[0];
          break;
        case 2:
          params.provinceId = value[0];
          params.cityId = value[1];
          break;
        case 3:
          params.provinceId = value[0];
          params.cityId = value[1];
          params.zoneId = value[2];
          break;
        case 4:
          params.provinceId = value[0];
          params.cityId = value[1];
          params.zoneId = value[2];
          params.streetId = value[3];
          break;

        default:
          break;
      }
    } else {
      params.region = [];
      params.provinceId = null;
      params.cityId = null;
      params.zoneId = null;
      params.streetId = null;
    }
  }
};
/**
 * @description:创建任务
 */
const addtask = () => {
  showTaskadd.value = true;
};

/**
 * @description: 关闭创建任务弹窗
 */
const Taskaddclose = () => {
  console.log("keyi");
  showTaskadd.value = false;
  importsuccess.value = false;
  selectsuccess.value = false;
  showuploadtable.value = false;
  //所有数据
  allData.value = [];
  //导入分页数据
  ImporttableList.value = [];
  //正常的数据
  normalData.value = [];
  //重复的数据
  repeatData.value = [];
  //异常的数据
  abnormalData.value = [];
  selectarray.value = [];
  if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection();
  }
};
/**
 * @description: 表格数据接口
 */
let taskFormRef = ref(null);
const submitaddtask = async () => {
  await taskFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let taskList = [];
          console.log(" normalData.value", normalData.value);
          normalData.value.forEach((item) => {
            taskList.push({
              policeStationId: item.policeStationId,
              institutionId: item.institutionId,
              provinceId: item.provinceId,
              cityId: item.cityId,
              zoneId: item.zoneId,
              streetId: item.streetId,
            });
          });
          let obj = {
            taskList: taskList,
            remark: taskForm.value.remark,
            lastDate: taskForm.value.lastDate + " 23:59:59",
          };
          addtasklist(obj).then((res) => {
            if (res.code == 200) {
              ElMessage.success(res.msg);
              showTaskadd.value = false;
              resetall();
              reset(1);
              gettaskList();
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  });
};
/**
 * @description: 重置为初始状态
 */
const resetall = () => {
  taskForm.value = {};
  //所有数据
  allData.value = [];
  //导入分页数据
  ImporttableList.value = [];
  //正常的数据
  normalData.value = [];
  //重复的数据
  repeatData.value = [];
  //异常的数据
  abnormalData.value = [];
  importsuccess.value = false;
  selectsuccess.value = false;
  selectarray.value = [];
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      showdialog.value = true;
      nextTick(() => {
        taskdetailref.value.handleDetailInfo(row);
      });
      break;
    case "check":
      showcheckreport.value = true;
      nextTick(() => {
        checkreportref.value.handleReport(row);
      });
      break;

    case "delete":
      ElMessageBox.confirm("此操作将删除该任务，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deltasklist(row.taskId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            gettaskList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/**
 * @description: 下载模板
 */
const download = () => {
  downloadTemplate().then((row) => {
    if (row) {
      var elink = document.createElement("a");
      elink.download = "导入模板.xlsx";
      elink.style.display = "none";
      var blob = new Blob([row], { type: "application/octet-stream" });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    } else {
      this.$message.error("下载异常，请联系管理员！");
    }
  });
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("institution_type").then((res) => {
    //单位类型下拉
    if (res.code === 200) {
      unittypeList.value = res.data;
    }
  });
  await getDictsApi("institution_industry_type").then((res) => {
    //行业主管下拉
    if (res.code === 200) {
      supervisorList.value = res.data;
    }
  });
  await getDictsApi("fkwz_institution_level_type").then((res) => {
    //单位级别下拉
    if (res.code === 200) {
      unitlevelList.value = res.data;
    }
  });
  await getDictsApi("query_institution_check_time_type").then((res) => {
    //单位级别下拉
    if (res.code === 200) {
      checktimeList.value = res.data;
    }
  });
  // await getAreaList({ pid: 0 }).then((res) => {
  //   options.value = res.data;
  // });
}

const handlerimport = (type) => {
  switch (type) {
    case 1:
      showImport.value = true;
      break;
    case 2:
      showselect.value = true;
      break;
    case 3:
      showinventory.value = true;
      inventorydata.value = normalData.value.slice(0, 10);
      break;

    default:
      break;
  }
};
let isUpload = ref(false);

const format = (percentage) =>
  percentage === 100 ? "上传中……" : `${percentage}%`;
const uploadSuccess = (res) => {
  console.log("执行");
  const { rows, total } = res;
  if (res.code === 200) {
    ElMessage.success("文件上传成功！");
    isUpload.value = false;
    allData.value = rows;
    importtotal.value = total;
    displayData(1);
    showuploadtable.value = true;
  } else {
    isUpload.value = false;
    ElMessage.error(res.msg);
  }
};

function beforeUpload(file) {
  console.log("heihei ");
  if (file.name.length > 50) {
    ElMessage.error(`文件名过长！最多只能上传50个文字的文件名文件！`);
    return false;
  }
  isUpload.value = true;
}
//导入数据的删除
const importdelete = (row) => {
  ElMessageBox.confirm("此操作将删除这条数据，是否继续？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
    type: "warning",
  })
    .then(async () => {
      const index = allData.value.indexOf(row);
      allData.value.splice(index, 1);
      displayData(importPage.value);
    })
    .catch(() => {});
};

//清单数据的删除
const inventorydelete = (row) => {
  ElMessageBox.confirm("此操作将删除这条数据，是否继续？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
    type: "warning",
  })
    .then(async () => {
      const index = normalData.value.indexOf(row);
      console.log("index", index);
      normalData.value.splice(index, 1);
      inventorydisplayData(inventoryparams.value.pageNum);
    })
    .catch(() => {});
};

//导入数据确认
const importsubimt = () => {
  if (repeatData.value.length > 0 || abnormalData.value.length > 0) {
    ElMessage.error(`请先处理重复和异常的数据!`);
    return;
  } else {
    importsuccess.value = true;
    showImport.value = false;
  }
};
//导入数据取消
const importcancel = () => {
  showuploadtable.value = false;
  //所有数据
  allData.value = [];
  //导入分页数据
  ImporttableList.value = [];
  //正常的数据
  normalData.value = [];
  //重复的数据
  repeatData.value = [];
  //异常的数据
  abnormalData.value = [];
};

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log("selection", selection);
  selectarray.value = selection;
}

//为每一列设置唯一标识
const getRowKey = (row) => {
  // 返回每一行数据的唯一标识符
  return row.institutionId; // 假设每一行数据都有一个 id 字段
};

//删除选择
const multipleTableRef = ref(null);
const deleteArray = (item, index) => {
  selectarray.value.splice(index, 1);
  unitList.value.forEach((ele) => {
    if (ele.institutionId == item.institutionId) {
      multipleTableRef.value.toggleRowSelection(ele, false);
    }
  });
};
//确认选择
const handlerselectunit = () => {
  if (selectarray.value.length > 0) {
    selectsuccess.value = true;
    normalData.value = selectarray.value;
    showselect.value = false;
  } else {
    ElMessage.error("请选择单位！");
  }
};
onMounted(() => {
  gettaskList();
  getunitList();
  checkRecordCount();
  getDicts();
  if (router.currentRoute.value.query.indexStrip) {
    addtask();
    // 使用 replace 方法更新路由
    router.replace({
      query: {},
    });
  }
});
</script>

<style scoped lang="scss">
.container {
  position: relative;
  .container-search {
    margin-bottom: 12px;
    .container-search-bottom {
      background-color: #ffffff;
      border-radius: 10px;
      padding: 15px 15px 15px 15px;
    }
  }

  .container-button {
    position: absolute;
    top: 15px;
    right: 15px;
    img {
      margin-right: 6px;
      margin-top: 2px;
    }
  }
  .container-table {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 15px 15px 15px 15px;
    .filter {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 460px;
      background: #ffffff;
      box-shadow: 0px 1px 4px 0px rgba(51, 51, 51, 0.1);
      border-radius: 20px;
      font-size: 14px;
      padding: 2px;
      margin-bottom: 10px;
      .filter-item {
        cursor: pointer;
        display: flex;
        align-items: center;
        padding: 10px 20px;
        border-radius: 20px;
        color: #7eb7fe;
        img {
          height: 16px;
          margin-right: 2px;
        }
      }
      .active {
        background-color: #4aa1fe;
        color: #ffffff;
      }
    }
    .check-tab {
      display: flex;
      .tab-item {
        display: flex;
        .tab {
          padding: 4px 12px;
          margin-right: 10px;
        }
        .tab-time {
          width: 110px;
          padding: 4px 12px;
        }
      }
      .orange {
        color: #ef8e4d;
        background-color: #f7e3c3;
        border-radius: 5px;
      }
      .green {
        color: #60cba7;
        background-color: #bbeddc;
        border-radius: 5px;
      }
    }
  }
}

.task-form {
  padding: 0 30px;
  .addunit {
    width: 100%;
    display: flex;
    flex-direction: column;
    .guide {
      cursor: pointer;
      width: 100%;
      background: #cae1f2;
      height: 26px;
      line-height: 26px;
      margin-top: 15px;
      color: #42abfa;
      text-indent: 2em;
    }
  }
}

.Import {
  padding: 0 30px 30px 30px;
  .item {
    display: flex;
    font-size: 12px;
    margin-bottom: 20px;
    .text {
      margin-left: 10px;
      color: #797979;
    }
  }
  .item:nth-child(1) {
    .text {
      color: #58e0ad;
    }
  }

  :deep(.el-upload-dragger) {
    padding: 0;
    width: 300px;
    height: 186px;
    margin: 0 auto;
    background-color: #f7fdff;
    border-radius: 10px;
  }
}

.Import-table {
  padding: 0 30px 20px 30px;
  .table-text {
    font-size: 14px;
    margin-bottom: 15px;
  }
}
.ai-select {
  display: flex;
  height: 610px;
  transform: translateY(-10px);
  color: #404141;
  .select-left {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 20%;
    padding: 30px 20px;
    background: #fafeff;
    box-shadow: 2px 2px 8px 0px rgba(0, 0, 0, 0.1);
    .item {
      .title {
        margin-bottom: 20px;
      }
    }

    .item-btn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
  .select-middle {
    padding: 0 20px;
    width: 60%;
    .middle-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 0;
    }
  }
  .select-right {
    width: 20%;
    background: #fafeff;
    box-shadow: -2px 2px 8px 0px rgba(0, 0, 0, 0.1);
    padding: 0px 20px;
    .right-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 0;
    }
    .right-content {
      height: 460px;
      overflow-y: scroll;
      .content-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f4f6f6;
        padding: 10px 0;
      }
    }
    .content-btn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}
</style>

<style>
.ImportdialogBox {
  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
}
</style>
